/*
 * Copyright 2002-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.security.web.csrf;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashSet;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.core.log.LogMessage;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * <p>
 * Applies
 * <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)" >CSRF</a>
 * protection using a synchronizer token pattern. Developers are required to ensure that
 * {@link CsrfFilter} is invoked for any request that allows state to change. Typically
 * this just means that they should ensure their web application follows proper REST
 * semantics (i.e. do not change state with the HTTP methods GET, HEAD, TRACE, OPTIONS).
 * </p>
 *
 * <p>
 * Typically the {@link CsrfTokenRepository} implementation chooses to store the
 * {@link CsrfToken} in {@link HttpSession} with {@link HttpSessionCsrfTokenRepository}.
 * This is preferred to storing the token in a cookie which can be modified by a client
 * application.
 * </p>
 * 1:该过滤器用于保护应用不受Csrf(跨站请求伪造)攻击：
 * 使用同步令牌模式应用CSRF保护。开发人员需要确保任何允许状态改变的请求都会调用CsrfFilter(即修改数据的请求)。
 * 通常这只是意味着他们应该确保他们的web应用程序遵循适当的REST语义(即不使用HTTP方法GET、HEAD、TRACE、OPTIONS改变状态，修改状态时使用post,put,delete等)。
 * 通常，CsrfTokenRepository实现选择将CsrfToken存储在HttpSession中，HttpSessionCsrfTokenRepository由LazyCsrfTokenRepository包装。
 * 这比将令牌存储在可由客户端应用程序修改的cookie中更可取
 * 2:CSRF攻击的原理是，当用户已经在某个网站认证完成后浏览器已存储用户的有效信息，攻击者诱导用户登录一个其他的网站，利用用户在原网站未过期的认证信息发起一个非用户本意的请求，比如：
 * 评论区增加恶意链接，是基于cookie获取用户信息的，因为路径匹配所以会获取当前登录用户信息，从而进行恶意攻击
 * 前后端分离后，前端先会访问后端获取一个token，然后将其存储在本地，对post方法拦截，将token增加到请求头中后端获取token跟保存在session中的token进行比对。此时如果
 * 在评论区增加一个恶意链接，点击相当于打开一个超链接，虽然cookie路径匹配会将cookie信息带入到后端，但它只是通过浏览器打开的一个get请求，其请求头是浏览器自带的，前端项目中定义
 * 拦截器不会对它进行处理，因为它并不是从项目内部发起的。 从而不会有token信息 所以可以解决跨站请求伪造问题
 * @author Rob Winch
 * @author Steve Riesenberg
 * @since 3.2
 */
public final class CsrfFilter extends OncePerRequestFilter {

	/**
	 * The default {@link RequestMatcher} that indicates if CSRF protection is required or
	 * not. The default is to ignore GET, HEAD, TRACE, OPTIONS and process all other
	 * requests.
	 */
	public static final RequestMatcher DEFAULT_CSRF_MATCHER = new DefaultRequiresCsrfMatcher();

	/**
	 * The attribute name to use when marking a given request as one that should not be
	 * filtered.
	 * <p>
	 * To use, set the attribute on your {@link HttpServletRequest}: <pre>
	 * 	CsrfFilter.skipRequest(request);
	 * </pre>
	 */
	private static final String SHOULD_NOT_FILTER = "SHOULD_NOT_FILTER" + CsrfFilter.class.getName();

	private final Log logger = LogFactory.getLog(getClass());
    //再configure中初始化时默认为HttpSessionCsrfTokenRepository
	private final CsrfTokenRepository tokenRepository;
    //默认实现为DefaultRequiresCsrfMatcher
	private RequestMatcher requireCsrfProtectionMatcher = DEFAULT_CSRF_MATCHER;

	private AccessDeniedHandler accessDeniedHandler = new AccessDeniedHandlerImpl();

	private CsrfTokenRequestHandler requestHandler = new XorCsrfTokenRequestAttributeHandler();

	/**
	 * Creates a new instance.
	 * @param tokenRepository the {@link CsrfTokenRepository} to use
	 */
	public CsrfFilter(CsrfTokenRepository tokenRepository) {
		Assert.notNull(tokenRepository, "tokenRepository cannot be null");
		this.tokenRepository = tokenRepository;
	}

	@Override
	protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
		return Boolean.TRUE.equals(request.getAttribute(SHOULD_NOT_FILTER));
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// 尝试从存储组件中加载CsrfToken 返回RepositoryDeferredCsrfToken对象
		DeferredCsrfToken deferredCsrfToken = this.tokenRepository.loadDeferredToken(request, response);
		//将deferredCsrfToken设置到request中的属性中
		request.setAttribute(DeferredCsrfToken.class.getName(), deferredCsrfToken);
		// 在Request中设置CsrfToken(里面封装了两个lambda) request.setAttribute(CsrfToken.class.getName(), csrfToken);
		// request.setAttribute(_csrf, csrfToken)
		// 注意：这里的lambda表达式会在OAuth2LoginAuthenticationFilter登录认证成功后通过OAuth2LoginConfigurer.onAuthentication方法进行调用，
		// 从而帮我们生成一个base64加密的csrfToken存储到session中，这样我们就可以通过response返回给前端，之后的请求前端携带该参数进入后端验证 每次登录后该值均不一样 从而避免跨站请求伪造
		// 默认情况下客户端一般需要先进行登录认证产生csrfToken返回给前端后再发起修改请求 如果直接发出修改请求那么此过滤器会进行拦截处理抛出异常
		this.requestHandler.handle(request, response, deferredCsrfToken::get);
		// 判断请求是否需要防止Csrf 默认忽略了("GET", "HEAD", "TRACE", "OPTIONS"） 这种不会改变数据 的请求方式
		// 再授权服务器时该路径匹配器还匹配了授权服务器的基础配置路径（code获取路径，token获取路径，token销毁路径等）
		if (!this.requireCsrfProtectionMatcher.matches(request)) {
			if (this.logger.isTraceEnabled()) {
				this.logger.trace("Did not protect against CSRF since request did not match "
						+ this.requireCsrfProtectionMatcher);
			}
			filterChain.doFilter(request, response);
			return;
		}
		// 获取CsrfToken ，session中有就返回 没有初始化一个token(UUID随机数生成)
		CsrfToken csrfToken = deferredCsrfToken.get();
		// 获取请求中携带的token(请求头或者请求参数中)
		String actualToken = this.requestHandler.resolveCsrfTokenValue(request, csrfToken);
		// 对比token
		if (!equalsConstantTime(csrfToken.getToken(), actualToken)) {
			// session中是否未携带token
			boolean missingToken = deferredCsrfToken.isGenerated();
			this.logger
				.debug(LogMessage.of(() -> "Invalid CSRF token found for " + UrlUtils.buildFullRequestUrl(request)));
			// 抛出异常
			AccessDeniedException exception = (!missingToken) ? new InvalidCsrfTokenException(csrfToken, actualToken)
					: new MissingCsrfTokenException(actualToken);
			// 调用异常处理器
			this.accessDeniedHandler.handle(request, response, exception);
			return;
		}
		filterChain.doFilter(request, response);
	}

	public static void skipRequest(HttpServletRequest request) {
		request.setAttribute(SHOULD_NOT_FILTER, Boolean.TRUE);
	}

	/**
	 * Specifies a {@link RequestMatcher} that is used to determine if CSRF protection
	 * should be applied. If the {@link RequestMatcher} returns true for a given request,
	 * then CSRF protection is applied.
	 *
	 * <p>
	 * The default is to apply CSRF protection for any HTTP method other than GET, HEAD,
	 * TRACE, OPTIONS.
	 * </p>
	 * @param requireCsrfProtectionMatcher the {@link RequestMatcher} used to determine if
	 * CSRF protection should be applied.
	 */
	public void setRequireCsrfProtectionMatcher(RequestMatcher requireCsrfProtectionMatcher) {
		Assert.notNull(requireCsrfProtectionMatcher, "requireCsrfProtectionMatcher cannot be null");
		this.requireCsrfProtectionMatcher = requireCsrfProtectionMatcher;
	}

	/**
	 * Specifies a {@link AccessDeniedHandler} that should be used when CSRF protection
	 * fails.
	 *
	 * <p>
	 * The default is to use AccessDeniedHandlerImpl with no arguments.
	 * </p>
	 * @param accessDeniedHandler the {@link AccessDeniedHandler} to use
	 */
	public void setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler) {
		Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null");
		this.accessDeniedHandler = accessDeniedHandler;
	}

	/**
	 * Specifies a {@link CsrfTokenRequestHandler} that is used to make the
	 * {@link CsrfToken} available as a request attribute.
	 *
	 * <p>
	 * The default is {@link XorCsrfTokenRequestAttributeHandler}.
	 * </p>
	 * @param requestHandler the {@link CsrfTokenRequestHandler} to use
	 * @since 5.8
	 */
	public void setRequestHandler(CsrfTokenRequestHandler requestHandler) {
		Assert.notNull(requestHandler, "requestHandler cannot be null");
		this.requestHandler = requestHandler;
	}

	/**
	 * Constant time comparison to prevent against timing attacks.
	 * @param expected
	 * @param actual
	 * @return
	 */
	private static boolean equalsConstantTime(String expected, String actual) {
		if (expected == actual) {
			return true;
		}
		if (expected == null || actual == null) {
			return false;
		}
		// Encode after ensure that the string is not null
		byte[] expectedBytes = Utf8.encode(expected);
		byte[] actualBytes = Utf8.encode(actual);
		return MessageDigest.isEqual(expectedBytes, actualBytes);
	}

	private static final class DefaultRequiresCsrfMatcher implements RequestMatcher {

		private final HashSet<String> allowedMethods = new HashSet<>(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS"));

		@Override
		public boolean matches(HttpServletRequest request) {
			return !this.allowedMethods.contains(request.getMethod());
		}

		@Override
		public String toString() {
			return "CsrfNotRequired " + this.allowedMethods;
		}

	}

}
